package xcmd

import (
	"errors"
	"fmt"
	"os"
	"regexp"
	"strings"

	"gitee.com/xiaoyutab/xgotool/xstring"
)

// 根据图片文件获取图片宽高，返回单位：px
//
//	filepath	图片地址
func Image2wh(filepath string) (uint, uint, error) {
	if err := CheckCommand("bash", "file", "sed", "cut"); err != nil {
		return 0, 0, err
	}
	if filepath == "" {
		return 0, 0, errors.New("文件路径不能为空")
	}
	if _, err := os.Stat(filepath); err != nil {
		// 文件不存在
		return 0, 0, errors.New("文件不存在")
	}
	filepath = strings.ReplaceAll(filepath, " ", "\\ ")
	out, err := Exec(GetCommand("file"), filepath)
	if err != nil {
		return 0, 0, err
	}
	reg, err := regexp.Compile(`^\d+\s*[xX]\s*\d+$`)
	if err != nil {
		return 0, 0, err
	}
	spl := strings.Split(out, ",")
	for _, s := range spl {
		s = strings.TrimSpace(s)
		if s == "" || !strings.Contains(s, "x") {
			continue
		}
		// 检测字符串是否符合 数字x数字 的格式
		if !reg.MatchString(s) {
			continue
		}
		tmp := strings.Split(s, "x")
		return xstring.ToUint(tmp[0]), xstring.ToUint(tmp[1]), nil
	}
	return 0, 0, fmt.Errorf("无法获取图片宽高：%s", out)
}
